﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using ICSharpCode.SharpZipLib.GZip;

namespace ExtBusiness.CommonBusiness
{
    public static class GZIP
    {
        public static String UnGZIPToString(byte[] bStream, String Charset)
        {
            return Encoding.GetEncoding(Charset).GetString(UnGZIP(bStream));
        }

        public static byte[] UnGZIP(byte[] bStream)
        {
            var ms = new MemoryStream(bStream);
            var outMemoryStream = new MemoryStream();
            var r = new byte[1024];
            using (var GZipStream = new GZipInputStream(ms))
            {
                int bytesRead;
                //未解压之前不知道解压后大小，所以只能循环读取
                while ((bytesRead = GZipStream.Read(r, 0, r.Length)) > 0)
                {
                    outMemoryStream.Write(r, 0, bytesRead);
                }
                return outMemoryStream.ToArray();
            }
        }

        public static byte[] GZIPCompress(byte[] pBytes)
        {
            var mMemory = new MemoryStream();
            using (var GZipStream = new GZipOutputStream(mMemory))
            {
                GZipStream.Write(pBytes, 0, pBytes.Length);
            }
            return mMemory.ToArray();
        }
    }
}
